<template>
  <div class="login">
    <van-nav-bar
      title="登录页面"
      left-text="返回"
      right-text="..."
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="block">
      <input
        type="elephone"
        placeholder="请输入手机号"
        v-model="formData.phone"
      />
    </div>
    <div class="block">
      <input type="password" placeholder="请输入密码" v-model="formData.pass" />
    </div>
    <div class="btn_login" @click="login">登录</div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { user_login } from "../utils/api";
export default {
  data() {
    return {
      formData: {
        phone: "",
        pass: "",
      },
    };
  },
  methods: {
    login() {
      if (/^1[3-9]\d{9}$/.test(this.formData.phone) == false) {
        Toast.fail("请输入合法的手机号");
      } else if (!this.formData.pass) {
        Toast.fail("请输入密码");
      } else {
        // 发请求登录
        user_login(this.formData).then((res) => {
          // 请求发送成功
          if (res.data.code == 200) {
            Toast.success(res.data.msg);
            // 保存登录信息
            localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo));
            // 保存token
            localStorage.setItem("token", res.data.token);
            // 登陆成功，请求当前用户的收藏列表
            this.$store.dispatch("request_favlist");
            // 请求当前用户地购物车列表
            this.$store.dispatch("request_shopcartlist");
            // 登录获取地址列表
            this.$store.dispatch("request_address_list");

            // 跳转页面
            this.$router.push("/");
          } else {
            Toast.fail(res.data.msg);
          }
        });
      }
    },
  },
};
</script>

<style>
.login .block {
  margin: 30px 20px;
}
.login .block input {
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding-left: 20px;
  box-sizing: border-box;
  outline: none;
  width: 100%;
}
.btn_login {
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding-left: 20px;
  text-align: center;
  margin: 30px 20px;
  line-height: 40px;
  background-color: rgb(56, 186, 243);
  color: #fff;
}
</style>